<template>
  <div class="container">
    <div class="center">
      <div class="card">
        <div class="additional">
          <div class="user-card">
            <div class="level center">
              {{userInfo.username}}
            </div>

            <template>
              <div class="user_pic">
                <img
                  v-if="userInfo.user_pic"
                  :src='userInfo.user_pic'
                  alt=""
                > <img
                  v-else
                  src="../../../../assets/avatar1.svg"
                  alt=""
                >
              </div>
            </template>

            <div class="points center">
              {{regTime}}
            </div>
          </div>
          <div class="more-info">
            <div class="stats">
              <div>
                <div class="title">发帖</div>
                <i class="fa fa-trophy"></i>
                <div class="value">{{userInfo.total_cards_number}}</div>
              </div>
              <div>
                <div class="title">回答</div>
                <i class="fa fa-gamepad"></i>
                <div class="value">{{userInfo.response_num}}</div>
              </div>
              <div>
                <div class="title">已注册</div>
                <i class="fa fa-group"></i>
                <div class="value">{{computedTime}}天</div>
              </div>

            </div>
          </div>
        </div>
        <div class="general">
          <div class="main">
            <div class="text">
              <h1>{{userInfo.username}}</h1>
              <p>{{userInfo.sign}}</p>

            </div>
            <div class="userinfo-foot">
              <div>
                <svg
                  class="icon"
                  aria-hidden="true"
                >
                  <use xlink:href="#icon-gender"></use>
                </svg><span>{{userInfo.gender}}</span>
              </div>
              <div>
                <svg
                  class="icon"
                  aria-hidden="true"
                >
                  <use xlink:href="#icon-ziyuan48"></use>
                </svg><span>{{userInfo.age}}</span>

              </div>
            </div>
          </div>

        </div>
      </div>
    </div>
    <el-button
      class="editInfo"
      type="primary"
      @click="drawer = true"
    >编辑资料</el-button>
    <el-drawer
      title="资料编辑"
      :visible.sync="drawer"
      direction="rtl"
      class="dialog"
    >
      <el-card class="box-card">
        <div class="checkImg">
          <div class="form-control">
            <label for="avatar">选择头像</label>
            <!-- 图像预览 -->
            <div class="pre_img">
              <!-- <div class="img-container">
              <li class="pro-img">
                <img
                  src=""
                  alt=""
                >
              </li>
            </div> -->
              <!-- 图片，用来展示用户选择的头像 -->
              <img
                class="the_img"
                v-if="!avatar"
                src="../../../../assets/avatar1.svg"
                alt=""
              />
              <!-- 这里preavatar是没有压缩的 -->
              <img
                class="the_img"
                v-else
                :src="preavatar"
              >
            </div>
            <div class="avatar">
              <ul
                class="avatars"
                id="login_avatar"
              >
                <li
                  v-for="index in 10"
                  :key="index"
                  @click="selectAvatar(index-1)"
                >
                  <img
                    :src="require(`../../../../assets/avatar${index}.svg`)"
                    alt=""
                  />
                </li>

              </ul>
            </div>
          </div>
          <!-- 按钮区域 -->
          <div class="btn-box">
            <input
              type="file"
              accept="image/*"
              style="display: none"
              ref="iptRef"
              @change="onFileChange"
            />
            <el-button
              type="primary"
              icon="el-icon-plus"
              @click="chooseImg"
            >选择图片</el-button>

          </div>
        </div>
        <!-- 头像 -->

        <!-- 表单 -->
        <el-form
          ref="userFormRef"
          label-width="100px"
        >
          <el-form-item
            label="用户名"
            prop="username"
          >
            <el-input
              disabled
              :value="userInfo.username"
            ></el-input>

          </el-form-item>
          <el-form-item
            label="性别"
            prop="gender"
          >
            <el-radio-group v-model="form.gender">
              <el-radio label="未知"></el-radio>
              <el-radio label="男"></el-radio>
              <el-radio label="女"></el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item
            label="年龄"
            prop="age"
          >
            <el-input v-model="form.age"></el-input>
          </el-form-item>
          <!-- <el-form-item>
            <el-button type="primary">提交修改</el-button>
            <el-button>重置</el-button>
          </el-form-item> -->
        </el-form>

        <div class="sign">
          <div>个性签名</div>
          <div class="userWords">
            <textarea
              class="message"
              placeholder="请输入..."
              v-model="form.sign"
            ></textarea>
          </div>
          <div class="submit-btn">
            <el-button
              type="success"
              icon="el-icon-upload"
              :disabled="avatar === ''"
              @click="uploadFn"
            >提交修改</el-button>
          </div>

        </div>
      </el-card>
    </el-drawer>
  </div>

</template>

<script>
import { mapState } from "vuex";
import { updateUserInfoAPI } from "@/api";
export default {
  data() {
    return {
      drawer: false,

      form: {
        gender: "",
        user_pic: "",
        age: "20",
        sign: "",
      },
      avatar: "", //链接或646字符串
      preavatar: "",
      filename: "",
      file: "",
    };
  },
  methods: {
    // 选择图片
    chooseImg() {
      this.$refs.iptRef.click();
    },
    onFileChange(e) {
      let files = e.target.files;
      if (files.length == 0) {
        // 证明没有选
      } else {
        // 证明选了一个
        this.file = e.target.files[0];

        this.filename = this.file.name;
        const reader = new FileReader(); //图片预览
        reader.readAsDataURL(this.file);
        reader.onload = (e) => {
          this.compressImage2(e.target.result); //处理图片
          // 这里用了两个 avatar 存数据 一个是没有压缩的 预览 一个是压缩的传过去
          this.preavatar = e.target.result;
          console.log("fff", this.preavatar);
        };
      }
    },

    // 上传图片
    async uploadFn() {
      console.log("fwefaw", this.formData);
      const res = await updateUserInfoAPI(this.formData);
      console.log("fwefwa", res);
      if (res.status !== 0) {
        this.$message.error(res.message);
      } else {
        this.$message.success(res.message);
        this.$store.dispatch("initUserInfo");
      }
    },
    // 压缩图片
    compressImage: function (bdata) {
      //压缩图片
      var _this = this;
      var quality = 1; //压缩图片的质量
      var oldimglength = bdata.length; //压缩前的大小
      var compresRadio = 0; // 压缩率

      var canvas = document.createElement("canvas"); //创建画布
      var ctx = canvas.getContext("2d");
      // 预览图
      _this.preavatar = bdata;
      var img = new Image();
      img.src = bdata;
      img.onload = function () {
        var width = img.width;
        var height = img.height;
        canvas.width = 100; //这里可以自定义你的图片大小
        canvas.height = 100 * (img.height / img.width);
        ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
        var cdata = canvas.toDataURL("image/jpeg", quality); //将图片转为Base64 之后预览要用

        _this.avatar = cdata; //预览你压缩后的图片
        _this.form.user_pic = cdata;
        var newimglength = cdata.length;
        console.log("211", _this.form.user_pic);
        console.log("img-blob:" + oldimglength); //压缩前大小
        console.log("ctx-blob:" + newimglength); //压缩后大小
        compresRadio =
          (((oldimglength - newimglength) / oldimglength) * 100).toFixed(2) +
          "%";
        console.log("压缩率:" + compresRadio);
      };
    },
    compressImage2: function (base64data) {
      var _this = this;
      var maxWidth = 800; // 设置最大宽度
      var maxHeight = 600; // 设置最大高度
      var quality = 0.75; // 设置压缩质量

      var img = new Image();

      img.onload = function () {
        var width = img.width;
        var height = img.height;

        // 计算压缩后的尺寸
        if (width > height) {
          if (width > maxWidth) {
            height *= maxWidth / width;
            width = maxWidth;
          }
        } else {
          if (height > maxHeight) {
            width *= maxHeight / height;
            height = maxHeight;
          }
        }

        var canvas = document.createElement("canvas");
        var ctx = canvas.getContext("2d");
        canvas.width = width;
        canvas.height = height;
        ctx.drawImage(img, 0, 0, width, height);

        // 将 Canvas 数据转换为 Base64 字符串
        var compressedData = canvas.toDataURL("image/jpeg", quality);

        // 设置预览图
        _this.preavatar = compressedData;
        _this.avatar = base64data;
        // 设置表单数据
        _this.form.user_pic = compressedData;
      };

      img.src = base64data;
    },

    // 选择图片
    selectAvatar(index) {
      document.querySelectorAll(".avatars >li").forEach((li) => {
        li.classList.remove("active");
      });
      document.querySelectorAll(".avatars >li")[index].classList.add("active");

      // 创建一个 Image 对象
      const img = new Image();
      img.onload = () => {
        // 创建一个 Canvas 元素
        const canvas = document.createElement("canvas");
        const ctx = canvas.getContext("2d");
        // 设置 Canvas 的大小与图片大小一致
        canvas.width = img.width;
        canvas.height = img.height;
        // 在 Canvas 上绘制 SVG 图片
        ctx.drawImage(img, 0, 0);
        // 将 Canvas 中的内容转换为 PNG 格式的 Base64 字符串
        const base64Data = canvas.toDataURL("image/png");
        // this.avatar = base64Data;
        // this.form.user_pic = base64Data;
        // this.preavatar = base64Data;
        this.compressImage2(base64Data);

        // 将 Base64 数据发送到后端保存
      };
      // 设置 Image 对象的 src 属性为 SVG 图片的路径，开始加载 SVG 图片
      img.src = require(`../../../../assets/avatar${index + 1}.svg`);
    },
  },
  computed: {
    ...mapState({
      userInfo: (state) => state.users.userInfo,
    }),

    formData() {
      return {
        ...this.userInfo,
        ...this.form,
      };
    },

    regTime() {
      return this.$formatDate(this.userInfo.moment);
    },
    computedTime() {
      return this.$computedTime(this.userInfo.moment);
    },
  },
};
</script>

<style scoped>
/* 选择头像抽屉 盒子 */
.checkImg {
  display: flex;
  width: 100%;
  justify-content: center;
  align-items: center;
  flex-direction: column;
}
::v-deep .el-form {
  display: flex;
  width: 100%;
  flex-direction: column;
  justify-content: center;
  align-items: flex-start;
  margin-top: 20px;
}
::v-deep .el-form-item {
  display: flex;
  width: 100%;
  justify-content: flex-start;
  align-items: center;
}
::v-deep .el-form-item__content {
  margin-left: 0 !important;
}
/* 抽屉颜色 */
::v-deep .el-drawer {
  background-color: #87a4ed !important;
}
::v-deep .el-card {
  background-color: #b1b9f0 !important ;
}

@import url("https://fonts.googleapis.com/css?family=Abel");

html,
body {
  background: #fceeb5;
  font-family: Abel, Arial, Verdana, sans-serif;
}

.user_pic {
  width: 140px;
  height: 140px;
  overflow: hidden;
  border-radius: 50%;
  border: 2px solid #fceeb5;
}
.user_pic > img {
  width: 100%;
  height: 100%;
}
.container {
  display: flex;
  flex-direction: column;
  gap: 20px; /* 设置子元素之间的间距 */
  width: 100%;
  position: relative;
  align-items: center;
  justify-content: flex-end;
}

.center {
  display: flex;
  position: absolute;
  top: 50%;
  left: 50%;
  -webkit-transform: translate(-50%, -50%);
}

.card {
  display: flex;
  width: 600px;
  height: 350px;
  background-color: #fff;
  background: linear-gradient(#f8f8f8, #fff);
  box-shadow: 0 8px 16px -8px rgba(0, 0, 0, 0.4);
  border-radius: 6px;
  overflow: hidden;
  position: relative;
  margin: 1.5rem;
}

.card h1 {
  text-align: center;
}

.card .additional {
  display: flex;
  position: absolute;
  width: 150px;
  height: 100%;
  background: linear-gradient(#de685e, #ee786e);
  transition: width 0.4s;
  overflow: hidden;
  z-index: 2;
}

.card.green .additional {
  background: linear-gradient(#92bca6, #a2ccb6);
}

.card:hover .additional {
  width: 100%;
  border-radius: 0 5px 5px 0;
}

.card .additional .user-card {
  display: flex;
  width: 150px;
  height: 100%;
  position: relative;
  float: left;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.card .additional .user-card::after {
  content: "";
  display: block;
  position: absolute;
  top: 10%;
  right: -2px;
  height: 80%;
  border-left: 2px solid rgba(0, 0, 0, 0.025);
}

.card .additional .user-card .level,
.card .additional .user-card .points {
  top: 15%;
  color: #fff;
  text-transform: uppercase;
  font-size: 0.75em;
  font-weight: bold;
  background: rgba(0, 0, 0, 0.15);
  padding: 0.125rem 0.75rem;
  border-radius: 100px;
  white-space: nowrap;
}

.card .additional .user-card .level {
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 1rem;
  width: 100px;
  text-align: center;
}
.card .additional .user-card .points {
  top: 85%;
}

.card .additional .user-card svg {
  top: 50%;
}

.card .additional .more-info {
  width: 300px;
  display: flex;
  float: left;
  position: absolute;
  left: 193px;
  height: 100%;
  justify-content: center;
  align-items: center;
}

.card .additional .stats {
  font-size: 2rem;
  width: 100%;
  display: flex;
  bottom: 1rem;
  top: auto;
  color: #fff;
}

.card.green .additional .stats {
  color: #325c46;
}

.card .additional .stats > div {
  flex: 1;
  text-align: center;
  margin-left: 20px;
}

.card .additional .stats i {
  padding: 10px;
  display: block;
}

.card .additional .stats div.title {
  font-size: 0.75rem;
  font-weight: bold;
  text-transform: uppercase;
}

.card .additional .stats div.value {
  font-size: 1.5rem;
  font-weight: bold;
  line-height: 1.5rem;
}

.card .additional .stats div.value.infinity {
  font-size: 2.5rem;
}

.card .general {
  display: flex;
  width: 300px;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100%;
  position: absolute;
  top: 0;
  right: 13%;
  z-index: 1;
  box-sizing: border-box;
  padding: 1rem;
  padding-top: 0;
  padding-right: 1.5rem;
}
.main {
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  align-items: center;
  position: relative;
  width: 100%;
  height: 80%;
}
.text {
  display: flex;
  position: absolute;
  top: 15%;
  flex-direction: column;
}
.text > h1 {
  margin-bottom: 1rem;
}

.icon {
  width: 30px;
  height: 30px;
}
.userinfo-foot {
  opacity: 0.5;
  display: flex;
  position: absolute;
  bottom: -10%;
  width: 100%;
}
.userinfo-foot > div {
  display: flex;
  text-align: center;
  justify-content: center;
  align-items: center;
  width: 50%;
}
.userinfo-foot > div > span {
  padding: 0 10px;
}
.editInfo {
  right: 0;
  bottom: 20px;
  margin-bottom: 5%;
}

/*头像 */

.form-control {
  display: flex;
  justify-content: center;
  flex-direction: column;
}

.avatar {
  margin-top: 1rem;
  width: 400px;
}
.avatar span {
  margin-top: 5px;
}
.avatar .avatars {
  width: 100%;
  min-height: 60%;
  border: 10px solid #667aff;
  border-radius: 20px;
  list-style: none;
  padding: 10px;
  box-sizing: border-box;
  display: grid;
  grid-template-rows: repeat(2, 1fr);
  grid-template-columns: repeat(5, 1fr);
  gap: 5px;
  justify-items: center;
  align-items: center;
  box-sizing: border-box;
}
.avatar .avatars li {
  height: 4rem;
  margin-bottom: 0.2rem;
  cursor: pointer;
  border-radius: 28px;
  overflow: hidden;
  box-sizing: border-box;
  box-sizing: border-box;
}

.avatar .avatars li img {
  width: 4rem;
}
.active {
  transition: all 0.1s;
  border: 4px solid #f7c924;
}
.the_img {
  width: 150px;
  height: 150px;
  border-radius: 100px;
  border: 5px solid #f7c924;
}
.pre_img {
  display: flex;
  justify-content: center;
  align-items: center;
}
/*头像按钮 */
.btn-box {
  display: flex;
  justify-content: center;
  margin-top: 10px;
}

/*个签 */
.sign {
  display: flex;
  flex-direction: column;
  margin-top: 20px;
}

.submit-btn {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 20px;
}
.userWords {
  display: flex;
  background-color: #acdccec3;
  margin-top: 4px;
  width: 100%;
  height: 150px;
  padding: 10px;
  justify-content: center;
  align-items: center;
  position: relative;
  box-sizing: border-box;
  font-family: cursive;
  font-size: 20px;
  border-radius: 10px;
  background: #fff;
  background-image: linear-gradient(#f5f5f0 1.1rem, #ccc 1.2rem);
  background-size: 100% 1.2rem;
  line-height: 1.45rem;
  padding: 0.5rem 0.2rem 0.1rem 0.1rem;
  margin-top: 10px;
}
/* textarea */
.message {
  background: none;
  /* border: none; */
  border: none;
  resize: none;
  outline: none;
  box-sizing: border-box;
  padding: 8px;
  width: 100%;
  height: 100%;
  margin-top: 12px;
}

.userWords > span {
  width: 96%;
  height: 90%;
  overflow: auto; /* 溢出隐藏 */
  text-align: center;
}
/*定义滚动条宽度和颜色*/

::v-deep .el-drawer__body::-webkit-scrollbar {
  width: 7px;
}

::v-deep .el-drawer__body::-webkit-scrollbar-track {
  background: #d2f3ef;
}

::v-deep .el-drawer__body::-webkit-scrollbar-thumb {
  background: #94f0f0;
}

/* 悬停效果 */
::v-deep .el-drawer__body::-webkit-scrollbar-thumb:hover {
  background: #5cd0f4;
}

.userWords-span::-webkit-scrollbar {
  width: 4px;
}

.userWords-span::-webkit-scrollbar-track {
  background: #d2f3ef;
}

.userWords-span::-webkit-scrollbar-thumb {
  background: #94f0f0;
}

/* 悬停效果 */
.userWords-span::-webkit-scrollbar-thumb:hover {
  background: #5cd0f4;
}

/* 结束 */
</style>